package cn.itcast.mobilebrowser.activity;

import androidx.appcompat.app.AppCompatActivity;
import cn.itcast.mobilebrowser.R;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.IOException;
import java.net.URL;

public class ShowWebImageActivity extends Activity {
    private static Drawable drawable;
    private String imagePath = null;
    private ImageView imageView = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_web_image);

        System.out.println("进入了ShowWebImageActivity.class");

        this.imagePath = getIntent().getStringExtra("url"); //获得图片Url
        imageView = (ImageView) findViewById(R.id.show_webimage_imageview);

        try {
            ShowWebImageActivity.loadImageFromUrl(this.imagePath,Thread.currentThread());   //调用方法
            Thread.sleep(3*1000);   //设置主线程暂停，执行子线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        imageView.setImageDrawable(drawable);   //把drawable图片在ImageView上显示
    }

    public static Drawable loadImageFromUrl(String url,Thread MainThread) {

        //涉及Stream需要通过子进程完成，重写run()执行loadImageFromUrl的方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    drawable = Drawable.createFromStream(new URL(url).openStream(), "src");
                    MainThread.interrupt();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();     //开启子进程

        return drawable;
    }

}